package com.houtai.controller.campus;


import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.houtai.authority.Authority;
import com.houtai.authority.AuthorityType;
import com.houtai.base.RetInfo;
import com.houtai.base.WangEditor;
import com.houtai.bean.TdCampus;
import com.houtai.bean.TsJzDict;
import com.houtai.bean.dto.campus.CampusLogin;
import com.houtai.common.Contant;
import com.houtai.common.oss.OssUtil;
import com.houtai.common.util.MD5;
import com.houtai.service.campus.CampusService;
import com.houtai.service.dict.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = {"v6"})
public class CampusController {


    @Autowired
    private CampusService campusService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DictService dictService;
    /**
     * @Purpose   登录
     * @param     campusLogin
     * @version   1.0
     * @author    李寻欢
     * @time      2018-07-09
     * @return    RetInfo
     */
    @RequestMapping(value="/logins")
    @ResponseBody
    @Authority(AuthorityType.NoValidate)
    public RetInfo login(CampusLogin campusLogin, HttpServletRequest request){
        return campusService.login(campusLogin, request);
    }
    /**
     * @Purpose   修改密码
     * @param     old_pass,user_pass
     * @version   1.0
     * @author    李寻欢
     * @time      2018-07-09
     * @return    RetInfo
     */
    @Authority(AuthorityType.Login)
    @RequestMapping(value = "/update/pass", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public RetInfo updatePass(String old_pass, String user_pass, HttpServletRequest request) {
        RetInfo retInfo = new RetInfo();

        TdCampus tdCampus = (TdCampus) redisTemplate.opsForValue().get(request.getParameter("token")) ;
        if (tdCampus.getCampus_psd().equals(MD5.code(old_pass))) {
            tdCampus.setCampus_psd(MD5.code(user_pass));
            retInfo = campusService.updateTdCampusPsd(tdCampus, request);
        } else {
            retInfo.setMark("1");
            retInfo.setTip("旧密码不对");
        }
        return retInfo;
    }
    /**
     * @Purpose   跳转到修改密码
     * @param
     * @version   1.0
     * @author    李寻欢
     * @time      2018-07-09
     * @return    ModelAndView
     */
    @Authority(AuthorityType.Login)
    @RequestMapping(value = "/to/update/pass", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toUpdatePass(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("campus/updatePass");
        mv.addObject("token", request.getParameter("token"));
        return mv;
    }
    /**
     * @Purpose  跳转到更新园区页面
     * @version  1.0
     * @author   lizhun
     * @param    request
     * @return   RetInfo
     */
    @RequestMapping(value="/campus/to/update")
    @Authority(AuthorityType.Login)
    public ModelAndView index(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("campus/update");
        TdCampus campus = (TdCampus) redisTemplate.opsForValue().get(request.getParameter("token")) ;
        TdCampus TdCampus = campusService.findTdCampusById(campus.getCampus_id());
        mv.addObject("token", request.getParameter("token"));
        mv.addObject("campus", TdCampus);
        List<TsJzDict> province = dictService.findTsJzDict("province");
        mv.addObject("province", province);
        mv.addObject("campus_type", dictService.findTsJzDict("campus_type"));
        mv.addObject("city", dictService.findAllDictByParentId(TdCampus.getProvince_id()));
        return mv;
    }
    /**
     * @Purpose   更新园区
     * @param     TdCampus
     * @version   1.0
     * @author    李准
     * @time      2017-08-19
     * @return    RetInfo
     */
    @RequestMapping(value = "/campus/update", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @Authority(AuthorityType.Login)
    public RetInfo update(@Valid TdCampus TdCampus, BindingResult result, HttpServletRequest request) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err = result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark("1");
            retInfo.setTip(fe.getDefaultMessage());
        } else {
            retInfo = campusService.updateTdCampus(TdCampus, request);
        }
        return retInfo;
    }
    /**
     *上传banner图片
     * @param frontFile
     * @return
     */
    @RequestMapping(value = "/campus/img" )
    @ResponseBody
    public Map<String, String> img(@RequestParam(value = "frontFile", required = true) MultipartFile frontFile)throws Exception{
        Map<String, String>  map = new HashMap<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssS", Locale.CHINA);

        String frontFileName = frontFile.getOriginalFilename().substring(frontFile.getOriginalFilename().lastIndexOf(".") + 1);
        String imgName = formatter.format(new Date(System.currentTimeMillis()));
        String frontSavePath = Contant.FILE_IMG+"/" + "campus/" + imgName + "." + frontFileName;
        ObjectMetadata frontMetadata = new ObjectMetadata();

        InputStream inputStream = frontFile.getInputStream();
        frontMetadata.setContentLength(inputStream.available());
        OssUtil.uploadInputStream(inputStream, frontMetadata, frontSavePath);
        map.put("mark", "0");
        map.put("tip", Contant.DOMAIN +  Contant.FILE_IMG+"/"+"campus"+"/"+imgName + "." + frontFileName);
        map.put("obj", imgName);

        return map;
    }
    /**
     *上传banner图片
     * @param frontFile
     * @return
     */
    @RequestMapping(value = "/campus/fileImg" )
    @ResponseBody
    public WangEditor fileImg(@RequestParam(value = "frontFile", required = true) MultipartFile frontFile)throws Exception{
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssS", Locale.CHINA);

        String frontFileName = frontFile.getOriginalFilename().substring(frontFile.getOriginalFilename().lastIndexOf(".") + 1);
        String imgName = formatter.format(new Date(System.currentTimeMillis()));
        String frontSavePath = Contant.FILE_IMG+"/" + "campus/" + imgName + "." + frontFileName;
        ObjectMetadata frontMetadata = new ObjectMetadata();

        InputStream inputStream = frontFile.getInputStream();
        frontMetadata.setContentLength(inputStream.available());
        OssUtil.uploadInputStream(inputStream, frontMetadata, frontSavePath);

        String[] str = { Contant.DOMAIN +  Contant.FILE_IMG+"/"+"campus"+"/"+imgName + "." + frontFileName};
        WangEditor we = new WangEditor(str);
        return we;
    }
}